package com.shujia.scala

import scala.io.Source

object Demo28Student {
  def main(args: Array[String]): Unit = {

    /**
      *
      * 2、统计总分大于年级平均分的学生 [学号，姓名，班级，总分]
      *
      */

    /**
      * 1、计算学生总分
      *
      */

    val scores = Source.fromFile("scala/data/score.txt").getLines().toList

    val kvScore = scores.map(line => {
      val split = line.split(",")
      val id = split(0)
      val score = split(2).toInt

      (id, score)
    })

    //通过学号进行分组
    val groupScore = kvScore.groupBy(kv => kv._1).toList


    //统计总分
    val sumScores = groupScore.map(kv => {
      val id = kv._1
      val ss: List[(String, Int)] = kv._2

      //计算每隔学生的总分
      val sumScore = ss.map(k => k._2).sum

      (id, sumScore)
    })


    /**
      * 2、计算年级平均分
      *
      */

    val meanScore = sumScores.map(kv => kv._2).sum / sumScores.length.toDouble

    println("平均分是：" + meanScore)

    /**
      * 3、 过滤总分大于年级平均分的学生
      *
      */

    val maxMeanStu = sumScores.filter(kv => {
      val sumScore = kv._2
      sumScore > meanScore
    })

    /**
      * 关联学生信息
      *
      */

    val students = Source.fromFile("scala/data/students.txt").getLines().toList

    val kvStudent = students.map(line => {
      val split = line.split(",")
      val id = split(0)
      val name = split(1)
      val clazz = split(4)
      (id, name + "\t" + clazz)
    }).toMap //kv格式的list集合可以直接转换成map集合


    val result = maxMeanStu.map(kv => {
      val id = kv._1
      val sumScore = kv._2

      //通过学号去学生信息map中取出学生信息
      val nameAndClazz = kvStudent.getOrElse(id, "null") //当学号不存在的时候返回null

      id + "\t" + nameAndClazz + "\t" + sumScore
    })

    result.foreach(println)

  }

}
